﻿#include "widget.h"
#include "ui_widget.h"
#include"SocketHelper.h"

#include <QDateTime>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->isOpen = false;
    connect(ui->ShowText,&QTextBrowser::textChanged,[=](){
        ui->ShowText->moveCursor(QTextCursor::End);  //将接收文本框的滚动条滑到最下面
    });
}

Widget::~Widget()
{
    delete ui;
}
//发送信息
void Widget::sendMessage(){
    m.messageType = 2;
    qDebug()<<ui->chatContent->toPlainText().toStdString().c_str();
    QString content= ui->chatContent->toPlainText();
    strcpy(m.messageContent+10,content.toStdString().c_str());
    strcpy(m.sender,sender.toStdString().c_str());
    strcpy(m.recevicer,recevicer.toStdString().c_str());
    qDebug()<<send(sockCli,(char*)&m,sizeof(m),0);
}
//窗口关闭事件
void Widget::closeEvent(QCloseEvent *event){
    this->isOpen = false;
}

void Widget::on_sendBtn_clicked()
{
    if(ui->chatContent->toPlainText().size() == 0) return;
    //1.发送消息
    sendMessage();
    //2.更新聊天窗
    QString preMessage = f->chatContent;
    QDateTime nowTime =QDateTime::currentDateTime();
    QString nowTimes =nowTime.toString("yyyy.MM.dd hh:mm:ss");
    QString nowMessage = preMessage + "\n"+nowTimes+"\n["+this->sender +"]"+ ui->chatContent->toPlainText();
    strcpy(f->chatContent,nowMessage.toStdString().c_str());
    qDebug()<<nowMessage;
    ui->ShowText->setText(nowMessage);
    ui->chatContent->setText("");
}

void Widget::keyReleaseEvent(QKeyEvent *event){
    if (event->key() == Qt::Key_Control)
    {
        if(ui->chatContent->toPlainText().size() == 0) return;
        //1.发送消息
        sendMessage();
        //2.更新聊天窗
        QString preMessage = f->chatContent;
        QDateTime nowTime =QDateTime::currentDateTime();
        QString nowTimes =nowTime.toString("yyyy.MM.dd hh:mm:ss");
        QString nowMessage = preMessage + "\n"+nowTimes+"\n["+this->sender +"]"+ ui->chatContent->toPlainText();
        strcpy(f->chatContent,nowMessage.toStdString().c_str());
        qDebug()<<nowMessage;
        ui->ShowText->setText(nowMessage);
        ui->chatContent->setText("");

    }
}
